//
//  CJWelcomeView.swift
//  SwiftDemo
//
//  Created by Chris on 2017/7/20.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit
import SDWebImage
class CJWelcomeView: UIView {

    /// 用户头像
    @IBOutlet weak var iconView: UIImageView!
    /// 用户昵称
    @IBOutlet weak var userNameL: UILabel!
    /// 用户头像距离底部的约束
    @IBOutlet weak var iconViewBottom: NSLayoutConstraint!
    
    /// 从xib中获取视图
    class func welcomeView() -> CJWelcomeView {
        
        let nib = UINib.init(nibName: "CJWelcomeView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! CJWelcomeView
        
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    /// 加载用户头像, 并对头像圆角化
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 加载用户头像
        guard let imageStr = CJNetworkManager.sharedManager.userAccount.avatar_large,
            let imageURL = URL(string: imageStr) else {
                return
        }
        iconView.sd_setImage(with: imageURL, placeholderImage: #imageLiteral(resourceName: "avatar_default_big"))
    }
    
    /// 当View显示时, 动画操作及隐藏
    override func didMoveToWindow() {
        super.didMoveToWindow()
        
        // 执行 didMoveToWindow 后, 控件Frame还没有计算好, 需要调用layoutIfNeeded
        self.layoutIfNeeded()
        
        // 设置用户头像动画结束后的约束
        iconViewBottom.constant = bounds.height - 200
        
        // 执行约束修改后的动画效果
        // usingSpringWithDamping为弹性效果
        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
            // 把修改约束转化为动画效果
            self.layoutIfNeeded()
        }) { (_) in
            // 用户名label动画方式显现
            UIView.animate(withDuration: 1.0, animations: { 
                self.userNameL.alpha = 1
            }, completion: { (_) in
                // 欢迎界面展示后, 移除当前界面, 进入首页
                self.removeFromSuperview()
            })
        }
    }
}
